---
title: Process and Code Execution
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

The Daytona SDK provides powerful process and code execution capabilities through the `process` module in Sandboxes. This guide covers all available process operations and best practices.

## Code Execution

Daytona SDK supports both stateless and stateful code execution flows. Stateless runs use the `process` module and
supports multiple languages (Python, TypeScript, JavaScript). The stateful code interpreter keeps variables and imports
between calls and currently supports only Python.

:::note

- Stateless execution inherits the Sandbox language that you choose at creation time. See [Basic Sandbox Creation](/docs/en/sandbox-management/#basic-sandbox-creation).
- The stateful interpreter supports only Python.
  :::

### Stateless Execution

Use stateless execution when each snippet is independent. Every invocation starts from a clean interpreter.

<Tabs syncKey="language">
<TabItem label="Python" icon="seti:python">
```python
# Run Python code
response = sandbox.process.code_run('''
def greet(name):
    return f"Hello, {name}!"

print(greet("Daytona"))
''')

print(response.result)
```
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
```typescript
// Run TypeScript code
let response = await sandbox.process.codeRun(`
function greet(name: string): string {
    return \`Hello, \${name}!\`;
}

console.log(greet("Daytona"));
`);
console.log(response.result);

// Run code with argv and environment variables
response = await sandbox.process.codeRun(
    `
    console.log(\`Hello, \${process.argv[2]}!\`);
    console.log(\`FOO: \${process.env.FOO}\`);
    `,
    { 
      argv: ["Daytona"],
      env: { FOO: "BAR" }
    }
);
console.log(response.result);

// Run code with timeout
response = await sandbox.process.codeRun(
    'setTimeout(() => console.log("Done"), 2000);',
    undefined,
    5000
);
console.log(response.result);
```
</TabItem>
</Tabs>

See: [code_run (Python SDK)](/docs/python-sdk/sync/process/#processcode_run), [codeRun (TypeScript SDK)](/docs/typescript-sdk/process/#coderun)

### Stateful Code Interpreter

When you need to persist variables, imports between calls, use the Sandbox code interpreter. It offers:

- A shared default context that keeps state between calls.
- The ability to create/delete isolated contexts for specific workflows.
- Per-call environment variables and timeout controls.

<Tabs syncKey="language">
<TabItem label="Python" icon="seti:python">
```python
from daytona import Daytona, OutputMessage

def handle_stdout(message: OutputMessage):
    print(f"[STDOUT] {message.output}")

daytona = Daytona()
sandbox = daytona.create()

# Shared default context
result = sandbox.code_interpreter.run_code(
    "counter = 1\nprint(f'Counter initialized at {counter}')",
    on_stdout=handle_stdout,
)

# Isolated context
ctx = sandbox.code_interpreter.create_context()
try:
    sandbox.code_interpreter.run_code(
        "value = 'stored in ctx'",
        context=ctx,
    )
    sandbox.code_interpreter.run_code(
        "print(value)",
        context=ctx,
        on_stdout=handle_stdout,
    )
finally:
    sandbox.code_interpreter.delete_context(ctx)
```
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
```typescript
import { Daytona } from '@daytonaio/sdk'

const daytona = new Daytona()

async function main() {
    const sandbox = await daytona.create()

    // Shared default context
    await sandbox.codeInterpreter.runCode(
`
counter = 1
print(f'Counter initialized at {counter}')
`,
        { onStdout: (msg) => process.stdout.write(`[STDOUT] ${msg.output}`)},
    )

    // Isolated context
    const ctx = await sandbox.codeInterpreter.createContext()
    try {
    await sandbox.codeInterpreter.runCode(
        `value = 'stored in ctx'`,
        { context: ctx },
    )
    await sandbox.codeInterpreter.runCode(
        `print(value)`,
        { context: ctx, onStdout: (msg) => process.stdout.write(`[STDOUT] ${msg.output}`) },
    )
    } finally {
    await sandbox.codeInterpreter.deleteContext(ctx)
    }
}

main()
```
</TabItem>
</Tabs>

See: [code_interpreter (Python SDK)](/docs/python-sdk/sync/code-interpreter) and [codeInterpreter (TypeScript SDK)](/docs/typescript-sdk/code-interpreter)

## Process Execution

Daytona SDK provides an option to execute shell commands and manage background processes in Sandboxes. The workDir for executing defaults to the current Sandbox working directory. Uses the WORKDIR specified in
the Dockerfile if present, or falling back to the user's home directory if not - e.g. `workspace/repo` implies `/my-work-dir/workspace/repo`, but you can override it with an absolute path (by starting the path with `/`).

### Running Commands

Daytona SDK provides an option to execute shell commands in Python and TypeScript. You can run commands with input, timeout, and environment variables.

<Tabs syncKey="language">
<TabItem label="Python" icon="seti:python">
```python
# Execute any shell command
response = sandbox.process.exec("ls -la")
print(response.result)

# Setting a working directory and a timeout

response = sandbox.process.exec("sleep 3", cwd="workspace/src", timeout=5)
print(response.result)

# Passing environment variables

response = sandbox.process.exec("echo $CUSTOM_SECRET", env={
        "CUSTOM_SECRET": "DAYTONA"
    }
)
print(response.result)

```
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
```typescript

// Execute any shell command
const response = await sandbox.process.executeCommand("ls -la");
console.log(response.result);

// Setting a working directory and a timeout
const response2 = await sandbox.process.executeCommand("sleep 3", "workspace/src", undefined, 5);
console.log(response2.result);

// Passing environment variables
const response3 = await sandbox.process.executeCommand("echo $CUSTOM_SECRET", ".", {
        "CUSTOM_SECRET": "DAYTONA"
    }
);
console.log(response3.result);

```

</TabItem>
</Tabs>

See: [exec (Python SDK)](/docs/python-sdk/sync/process/#processexec), [executeCommand (TypeScript SDK)](/docs/typescript-sdk/process/#executecommand)

## Sessions (Background Processes)

Daytona SDK provides an option to start, stop, and manage background process sessions in Sandboxes. You can run long-running commands, monitor process status, and list all running processes.

### Managing Long-Running Processes

Daytona SDK provides an option to start and stop background processes. You can run long-running commands and monitor process status.

<Tabs syncKey="language">
<TabItem label="Python" icon="seti:python">
```python
# Check session's executed commands
session = sandbox.process.get_session(session_id)
print(f"Session {process_id}:")
for command in session.commands:
    print(f"Command: {command.command}, Exit Code: {command.exit_code}")

# List all running sessions

sessions = sandbox.process.list_sessions()
for session in sessions:
    print(f"PID: {session.id}, Commands: {session.commands}")

```
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
```typescript
// Check session's executed commands
const session = await sandbox.process.getSession(sessionId);
console.log(`Session ${sessionId}:`);
for (const command of session.commands) {
    console.log(`Command: ${command.command}, Exit Code: ${command.exitCode}`);
}

// List all running sessions
const sessions = await sandbox.process.listSessions();
for (const session of sessions) {
    console.log(`PID: ${session.id}, Commands: ${session.commands}`);
}

```

</TabItem>
</Tabs>

See: [get_session (Python SDK)](/docs/python-sdk/sync/process/#processget_session), [list_sessions (Python SDK)](/docs/python-sdk/sync/process/#processlist_sessions), [getSession (TypeScript SDK)](/docs/typescript-sdk/process/#getsession), [listSessions (TypeScript SDK)](/docs/typescript-sdk/process/#listsessions)

## Best Practices

Use the following best practices when working with process and code execution in Daytona SDK.

### Resource Management

The following best practices apply to managing resources when executing processes:

1. Use [sessions](#sessions-background-processes) for long-running operations
2. Clean up sessions after execution
3. Handle session exceptions properly

<Tabs syncKey="language">
<TabItem label="Python" icon="seti:python">
   ```python
   # Python - Clean up session
   session_id = "long-running-cmd"
   try:
       sandbox.process.create_session(session_id)
       session = sandbox.process.get_session(session_id)
       # Do work...
   finally:
       sandbox.process.delete_session(session.session_id)
   ```
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
   ```typescript
   // TypeScript - Clean up session
   const sessionId = "long-running-cmd";
   try {
       await sandbox.process.createSession(sessionId);
       const session = await sandbox.process.getSession(sessionId);
       // Do work...
   } finally {
       await sandbox.process.deleteSession(session.sessionId);
   }
   ```
</TabItem>
</Tabs>

See: [create_session (Python SDK)](/docs/python-sdk/sync/process/#processcreate_session), [delete_session (Python SDK)](/docs/python-sdk/sync/process/#processdelete_session), [createSession (TypeScript SDK)](/docs/typescript-sdk/process/#createsession), [deleteSession (TypeScript SDK)](/docs/typescript-sdk/process/#deletesession)

### Error Handling

The following best practices apply to error handling when executing processes:

- Handle process exceptions properly
- Log error details for debugging
- Use try-catch blocks for error handling

<Tabs syncKey="language">
<TabItem label="Python" icon="seti:python">
```python
try:
    response = sandbox.process.code_run("invalid python code")
except ProcessExecutionError as e:
    print(f"Execution failed: {e}")
    print(f"Exit code: {e.exit_code}")
    print(f"Error output: {e.stderr}")
```
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
```typescript
try {
    const response = await sandbox.process.codeRun("invalid typescript code");
} catch (e) {
    if (e instanceof ProcessExecutionError) {
        console.error("Execution failed:", e);
        console.error("Exit code:", e.exitCode);
        console.error("Error output:", e.stderr);
    }
}
```
</TabItem>
</Tabs>

## Common Issues

To troubleshoot common issues related to process and code execution, refer to the following table:

| Issue | Solutions |
|-------|-----------|
| `Process Execution Failed` | • Check command syntax<br/>• Verify required dependencies<br/>• Ensure sufficient permissions |
| `Process Timeout` | • Adjust timeout settings<br/>• Optimize long-running operations<br/>• Consider using background processes |
| `Resource Limits` | • Monitor process memory usage<br/>• Handle process cleanup properly<br/>• Use appropriate resource constraints |
